import time
import os
import datetime
import logging
import random
import uiautomator2 as u2
from uiautomator2.exceptions import ConnectError


PHONES = {
    "lauz": "10.168.3.200",
    # "zxh": "10.168.3.115",
}


def wait_a_minute(max_minute=1):
    time.sleep(int(random.random() * 60 * max_minute))


def is_morning():
    now = datetime.datetime.now()
    # today = now.strftime('%Y-%m-%d')
    # weekday = now.weekday()
    return now.hour < 12   


def start_work(user):
    phone = PHONES[user]
    try:
        # u = u2.connect("K6T6R17424001306")
        # u = u2.connect_wifi("10.168.3.200")
        u = u2.connect_adb_wifi(phone+":5555")
    except:
        logging.error(f"fail to {user}")
        exit(-1)
    # swipe to unlock
    u.screen_on()
    u.swipe_ext("up", scale=0.9)
    time.sleep(1)

    # open app
    u.app_start('com.tencent.wework', stop=True)
    time.sleep(3)

    # click
    u(text='工作台').click()
    time.sleep(1)
    u.swipe_ext("up", scale=0.2)
    time.sleep(1)
    u(text='打卡').click()
    time.sleep(1)

    if u(text="今天不上班，好好休息").exists:
        msg = "今天不上班，好好休息"
    else:
        if u(text="上班打卡").exists and is_morning():
            u(text="上班打卡").click()
            msg = "上班打卡"

        elif u(text="下班打卡").exists and not is_morning():
            u(text="下班打卡").click()
            msg = "下班打卡"
        else:
            msg = "打卡失败"
    
    # exit
    time.sleep(3)
    u.app_stop('com.tencent.wework')
    u.press("home")
    u.screen_off()

    os.popen("adb disconnect")
    return msg


def main():
    logging.basicConfig(level=logging.INFO, filename='wework.log',
                        format='%(asctime)s - %(levelname)s - %(message)s')
 

    logging.debug('start work')
    for user in PHONES:
        msg = start_work(user)
        logging.info(user + " " + msg)
        wait_a_minute()


if __name__ == '__main__':
    # wait a random second
    wait_a_minute()
    main()